import 'package:battery_plus/battery_plus.dart';
import 'package:flutter/material.dart';
import 'package:furaha_mkopo/commonTool/fm_jump_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_location_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_report_event_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_route_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_progress_hud.dart';
import 'package:furaha_mkopo/commonUI/fm_toast.dart';
import 'package:furaha_mkopo/manager/fm_device_manager.dart';
import 'package:furaha_mkopo/manager/fm_global_manager.dart';
import 'package:furaha_mkopo/page/home/api/fm_home_api.dart';
import 'package:furaha_mkopo/page/home/api/fm_home_click_access_api.dart';
import 'package:furaha_mkopo/page/home/api/fm_home_detail_api.dart';
import 'package:furaha_mkopo/page/home/entity/fm_home_click_access_entity.dart';
import 'package:furaha_mkopo/page/home/entity/fm_home_detail_entity.dart';
import 'package:furaha_mkopo/page/home/entity/fm_home_entity.dart';
import 'package:furaha_mkopo/page/home/enum/fm_home_net_enum.dart';
import 'package:furaha_mkopo/page/home/enum/fm_home_page_enum.dart';
import 'package:furaha_mkopo/page/home/fm_home_detail_page.dart';
import 'package:furaha_mkopo/page/login/fm_login_page.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class FMHomeController extends GetxController {
  FMHomeNetEnum netEnum = FMHomeNetEnum.loading;
  FMHomePageEnum pageEnum = FMHomePageEnum.big;
  FMHomeEntity? fmHomeEntity;
  FMHomeBeamedEntity? beamedEntity;
  DateTime lastUpdateDate = DateTime.now();

  String get lastUpdateDateStr => DateFormat('yyyy-MM-dd HH:mm:ss').format(lastUpdateDate);

  bool isFirstLoad = false;

  @override
  void onInit() {
    super.onInit();
    initBattery();
  }

  void onRefreshData({int reconnectCount = 0,RefreshController? refreshController}) {
    FMProgressHud.showLoading();
    netEnum = FMHomeNetEnum.loading;
    FMHomeApi api = FMHomeApi();
    lastUpdateDate = DateTime.now();
    api
        .send<FMHomeEntity, FMHomeEntity>(decodeType: FMHomeEntity())
        .then((value) {
      FMProgressHud.hideLoading();
      if (value.data == null && reconnectCount > 0) {
        onRefreshData(reconnectCount: reconnectCount - 1);
        return;
      }
      if (value.data == null) {
        netEnum = FMHomeNetEnum.error;
        FMToast.showText(value.message ?? "Network request error");
        refreshController?.refreshFailed();
        update();
        return;
      }
      fmHomeEntity = value.data!;
      _judgePageEnum();
      netEnum = FMHomeNetEnum.success;
      refreshController?.refreshCompleted();
      
      reportData();
      
      update();
    });
  }

  void checkNeedPopLocation() {
    if (!isFirstLoad) {
      isFirstLoad = true;
      FMLocationTool.checkAccess();
    }
  }

  DecorationImage? getDecorationImage() {
    String bgPath = pageEnum == FMHomePageEnum.big
        ? "assets/home/ic_big_bg.webp"
        : "assets/home/ic_small_top_bg.webp";
    return fmHomeEntity != null
        ? DecorationImage(
            image: AssetImage(bgPath),
            fit: BoxFit.fill,
          )
        : null;
  }

  void _judgePageEnum() {
    for (int i = 0; i < (fmHomeEntity!.beamed?.length ?? 0); i++) {
      FMHomeBeamedEntity beamedEntity = fmHomeEntity!.beamed![i];
      if(beamedEntity.firm == "appeared"){
        pageEnum = FMHomePageEnum.big;
        this.beamedEntity = beamedEntity;
        break;
      }else if(beamedEntity.firm == "that"){
        pageEnum = FMHomePageEnum.small;
        this.beamedEntity = beamedEntity;
        break;
      }
    }
  }

  initBattery() async {
    final Battery battery = Battery();
    final level = await battery.batteryLevel;

    battery.onBatteryStateChanged.listen((BatteryState state) {
      FMDeviceManager().batteryState = state == BatteryState.charging;
    });

    FMDeviceManager().batteryLevel = level.toString();

  }
  
  void reportData() {
    FMReportEventTool.reportLocation();
    FMReportEventTool.reportDevice();
    FMReportEventTool.reportGoogleMarket();
  }
}
